package com.core.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.managers.LoginManager;
import com.core.managers.SessionManager;
import com.core.utils.GlobalConstants;

public class FilterAccess
        implements Filter {


	private FilterConfig filterConfig = null;



	public void init ( final FilterConfig fConfig )
	        throws ServletException {

		this.filterConfig = fConfig;
	}



	@Override
	public void destroy () {

		//
	}



	public FilterConfig getFilterConfig () {

		return filterConfig;
	}



	public void setFilterConfig ( final FilterConfig filterConfig ) {

		this.filterConfig = filterConfig;
	}



	public void doFilter ( final ServletRequest request,
	                       final ServletResponse response,
	                       final FilterChain chain )
	        throws IOException, ServletException {



		final HttpServletRequest httpRequest = (HttpServletRequest) request;
		final HttpServletResponse httpResponse = (HttpServletResponse) response;

		final LoginManager loginManager = LoginManager.sharedInstance();

		boolean isLoginFormDisplaying = loginManager.isLoginFormDisplaying();
		if ( !loginManager.hasClosedAllLoginForms() ) {
			if ( loginManager.isLoginGetMethodExecuted() ) {
				loginManager.resetLoginformOpenAttepts();
				loginManager.setLoginGetMethodExecuted(false);

			} else {
				isLoginFormDisplaying = false;
			}
		}

		boolean isValidUser = false;
		if ( !isLoginFormDisplaying ) {
			isValidUser = loginManager.isValidUser();
			if ( !isValidUser ) {
				final String userName = SessionManager.sharedInstance().cookieValue((HttpServletRequest) request, "userName");
				final String userPassword = SessionManager.sharedInstance().cookieValue((HttpServletRequest) request, "userPassword");
				isValidUser = loginManager.performUserCheck(userName, userPassword);
				if ( !isValidUser ) {
					loginManager.doDefaultRedirection(httpRequest, httpResponse);
				}
			}
		}

		String servletPath = httpRequest.getServletPath();
		boolean useDefaultRedirect = (servletPath == null);
		if ( !useDefaultRedirect ) {
			useDefaultRedirect = ("/".equalsIgnoreCase(servletPath));
		}
		if ( isLoginFormDisplaying ) {
			chain.doFilter(request, response);
		} else {
			if ( isValidUser ) {
				if ( useDefaultRedirect ) {
					httpResponse.sendRedirect(GlobalConstants.SERVLET_DASHBOARD);
				} else {
					chain.doFilter(request, response);
				}
			}
		}
	}


}
